<template>
  <el-container>
    <el-main>
      <div class="search-container">
        <el-form ref="form" label-position="top" :rules="rules" :model="form" label-width="80px">
          <h2 style="text-align: center; color: #7d8995"><i class="el-icon-edit-outline" />修改博客</h2>
          <el-form-item prop="title">
            <span slot="label" style="color: #333333;  font-weight: bold">标题：</span>
            <el-input v-model="form.title" />
          </el-form-item>
          <el-form-item prop="content">
            <span slot="label" style="color: #333333;  font-weight: bold">内容：</span>
            <mavon-editor ref="md" v-model="form.content" :autofocus="false" placeholder="支持markdown和katex公式 " @imgAdd="imgAdd" />
          </el-form-item>
          <el-form-item>
            <el-checkbox v-model="form.isPublic" :true-label="1" :false-label="0">公开</el-checkbox>
          </el-form-item>
          <el-form-item>
            <el-button type="success" style="font-weight: bold" @click="onSubmit">确定</el-button>
          </el-form-item>
        </el-form>
      </div>
    </el-main>
  </el-container>
</template>

<script>
import { newBlog } from '@/networks/blog'
import { imgAdd } from '@/networks/info'

export default {
  name: 'UpdateBlog',
  data() {
    return {
      form: {
        content: '',
        title: '',
        isPublic: 0,
        id: ''
      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' }
        ],
        content: [
          { required: true, message: '请输入内容', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    if (this.$route.params.form != null) {
      this.form = this.$route.params.form
    }
  },
  methods: {
    onSubmit() {
      this.$refs.form.validate((valid) => {
        if (!valid) return false
        if (this.form.id !== '') {
          newBlog(this.form)
            .then(res => {
              const data = res.data
              this.$message.success(data.msg)
              this.$router.push('/blog')
            })
        } else {
          this.$message.error('更新失败')
        }
      })
    },
    imgAdd(pos, $file) {
      // 第一步.将图片上传到服务器.
      const form = new FormData()
      form.append('file', $file)
      imgAdd(form).then(res => {
        this.$refs.md.$img2Url(pos, res.data.data)
      })
    }
  }
}
</script>

<style scoped>
  .search-container {
    margin-left: auto !important;
    margin-right: auto !important;
    width: 1200px;
    height: auto;
    background-color: #ffffff;
    box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04);

  }

  .el-form {
    padding: 20px;
  }
</style>
